var express=require('express')
var Router=express.Router()
var fs=require('fs')
var config=require('./config.js')
//白名单
var list=config.whitelist;
//查询是否存在白名单
function findIp(ip){
	ip=String(ip)
	var flag=false;
	list.forEach(item=>{
		if(ip.indexOf(item)!=-1)
			flag=true;
	})
	flag=true;
	return flag;
}


function OpenCors(res){
	res.setHeader("Access-Control-Allow-Origin", "*");
	res.setHeader('Access-Control-Allow-Methods','*');
	res.setHeader("Access-Control-Allow-Headers", "x-token-shitian");
}
Router.use('/',(req,res,next)=>{
	console.log('放行')
	if(!config.blacklist){
	 OpenCors(res)
		next()
		console.log('黑名单未启动')
		return;
	}
	var ip=req.headers['origin']||Math.random();
	if(findIp(ip)){
		console.log('白名单'+ip)
		OpenCors(res)
		next()
	}else{
		var Not404=fs.readFileSync('./404.html')
		res.end(Not404)
		console.log('黑名单',ip)
	}
})


module.exports= Router